package com.studentportalen;

import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;

public class ExamsActivity extends ListActivity {

	private int studentId;
	private ExamSimpleCursorAdapter adapter;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exams);
        
        //Get data from intent
        Bundle extras = getIntent().getExtras();
        if(extras != null){
        	studentId = extras.getInt("studentId");
        }
        
        //Get data from db
        DBHelper db = Global.getDBHelper();
        Cursor c = db.getStudentRegistered(studentId);

        // create an array to specify which fields we want to display
        String[] from = new String[]{"name", "info"};
        // create an array of the display item we want to bind our data to
        int[] to = new int[]{R.id.list_exam_course, R.id.list_exam_info};
        
        adapter = new ExamSimpleCursorAdapter(this, R.layout.list_item_exams, c, 
        		from, to, studentId);
        
        //put data into list adapter
        setListAdapter(adapter);
    }
    
    /***
     * Registers the student on the selected courses
     * @param view
     */
    public void updateRegistration(View view){
    	DBHelper db = Global.getDBHelper();
    	
    	View v;
    	CheckBox cb;
    	ListView lvItems = getListView();
    	
    	//go through all courses and update registration status
        for (int i=0; i < lvItems.getChildCount(); i++) 
        {
            v = lvItems.getChildAt(i);
            cb = (CheckBox)v.findViewById(R.id.list_exam_checkbox);
            if(cb.isChecked()){
            	//Register student for course
            	try{
            		db.registerForExam(studentId, (int)lvItems.getItemIdAtPosition(i), (int)(Math.random()*100));
            	}
            	catch(Exception ex){
            		//notify user that he is already registered
            	}
            } else {
            	//Unregisters student for course
            	db.unregisterForExam(studentId, (int)lvItems.getItemIdAtPosition(i));
            }
        }
        //update listview
        adapter.notifyDataSetChanged();
        
        Toast.makeText(getApplicationContext(), "Registration for exams done.", Toast.LENGTH_LONG).show();
    }

}
